package com.cungmua.app.task;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.cungmua.app.R;
import com.cungmua.app.handler.BaseRequestHandler;
import com.cungmua.app.net.CungMuaAPI;
import com.cungmua.app.net.CungMuaService;

import retrofit.RetrofitError;

/**
 * Created by kelvin.nguyen on 6/16/14.
 */
public abstract class BaseRequestTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
    RetrofitError exception;
    Params[] params;
    private ProgressDialog dialog;
    CungMuaService service;

    protected BaseRequestTask() {
        service = CungMuaAPI.getService();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = ProgressDialog.show(getContext(), "Loading...", getContext().getString(R.string.loading));
        dialog.show();
    }

    @Override
    protected Result doInBackground(Params... params) {
        this.params = params;
        try {
            return doInBackground();
        } catch (RetrofitError e) {
            this.exception = e;
            return null;
        }
    }

    @Override
    protected void onPostExecute(Result result) {
        dialog.dismiss();
        super.onPostExecute(result);
        if (exception == null) {
            onSuccess(result);
        } else if (exception.isNetworkError()) {
            onNetworkError(exception);
        } else {
            onNetworkError(exception);
            exception.printStackTrace();
            //throw new RuntimeException(exception);
        }
    }

    protected void onNetworkError(Exception e) {
        getHandler().onNetworkError(e);
    }

    protected abstract Context getContext();

    protected abstract Result doInBackground() throws RetrofitError;

    protected abstract BaseRequestHandler getHandler();

    protected abstract void onSuccess(Result result);
}
